<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
class Commonlink extends Controller
{
    /**
     * @param $url
     * @param $post_data
     * @return mixed
     */
    public function curl_post($url,$post_data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,            $url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POST,           1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($post_data));// 必须为字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain'));// 必须声明请求头
        $return = curl_exec($ch);
        curl_close($ch);
        return $return = json_decode($return);
    }

    public function curl_get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,            $url );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }
     public function produceSN()
    {
        //生成编号
        $max = db('cg_ti')->where('sn', 'like', date('Ymd') . '%')->max('sn'); //编号递增开始位置基础

        if ($max) {
            $max = (double)$max;
            $insert_sn = $max + 1;
        } else {
            $insert_sn = date('Ymd') . '0001';
        }
        return $insert_sn;
    }

    public $typearr=[
                        5=>["name"=>"出差申请","table"=>"chuchai_apply"],
                        6=>["name"=>"万用申请","table"=>"wanneng_apply"],
                        7=>["name"=>"经销商合同申请","table"=>"jxs_hetong"],
                        8=>["name"=>"预算及目标申请","table"=>"target_apply"],
                        9=>["name"=>"预算及目标异动申请","table"=>"target_apply"],
                        10=>["name"=>"日常费用报销申请","table"=>"rc_baoxiao_apply"],
                        11=>["name"=>"AP费用申请","table"=>"ap_apply"],
                        12=>["name"=>"AP费用取消","table"=>"ap_apply"],
                        13=>["name"=>"AP费用异动","table"=>"ap_apply"],
                        14=>["name"=>"AP费用反馈","table"=>"ap_fankui"],
                        15=>["name"=>"AP费用核销","table"=>"ap_hexiao_apply"],
                        16=>["name"=>"AP补发票申请","table"=>"apti_fp_apply"],
                        17=>["name"=>"TI费用反馈","table"=>"all_ti_feeback_list"],
                        18=>["name"=>"TI费用核销","table"=>"cg_ti_hexiao"],
                        19=>["name"=>"TI补发票申请","table"=>"apti_fp_apply"],
                        20=>["name"=>"渠道优惠政策申请","table"=>"cg_channel_preferential_policy"],
                        21=>["name"=>"TI费用异动申请","table"=>"cg_ti"],
                        22=>["name"=>"TI费用取消申请","table"=>"cg_ti"],
                        23=>["name"=>"订单申请","table"=>"cg_order"],
                        24=>["name"=>"TPM专项费用申请","table"=>"ti_apply"],
                        25=>["name"=>"网点目标申请","table"=>"target_net_apply"],
                        26=>["name"=>"网点目标异动","table"=>"target_net_apply"],
                        27=>["name"=>"请假申请","table"=>"yd_qjsq"],
                        28=>["name"=>"加班申请","table"=>"jiaban_apply"]
                    ];
    public $targetarr=[
            1=>["id"=>1,"name"=>"集团目标格式","controller"=>"Jituanmubiao"],
            2=>["id"=>2,"name"=>"TI费用预算格式","controller"=>"Tiyusuan"],
            3=>["id"=>3,"name"=>"AP费用预算格式","controller"=>"Apyusuan"],
            4=>["id"=>4,"name"=>"日常费用预算格式","controller"=>"Rcyusuan"],
            5=>["id"=>5,"name"=>"经销商销售目标格式","controller"=>"Jingxiaomubiao"]
        ];
    //ti返回
    public function tiback($aid,$nodeId){
      //echo 1;
      if($nodeId=="Node3"){
          //拆分人审批
          
          Db::table("cg_ti")->where(["id"=>$aid])->update(["status"=>4]);
       }else if($nodeId=="Node6"){
          //集团领导审批
          Db::table("cg_ti")->where(["id"=>$aid])->update(["status"=>5]);
       }else if($nodeId=="Node8"){
          //修改申请表
          Db::table("cg_ti")->where(["id"=>$aid])->update(["status"=>2]);
          $type_id=Db::table("cg_ti")->where(["id"=>$aid])->value("type_id");
          if($type_id!=1){
            $ap=Db::table("cg_ti_list")->where(["ti_id"=>$aid])->select();
          for($i=0;$i<count($ap);$i++){
            $up["id"]=$ap[$i]["id"];
            $up["pizhunweishui"]=$ap[$i]["amount"];
            $up["pizhunhanshui"]=$ap[$i]["hanshui"];$up["yjsjtrfy"]=$ap[$i]["hanshui"];
            $up["isOrNo"]=1;$up["yujifeiyonglv"]=$up["pizhunhanshui"]/$ap[$i]["totalExpectedSales"]*100;
            if($ap[$i]["product"]){
                                    $profit=db("pro_products")->alias("p")
                                    ->join("pro_sku sk","p.sku_id=sk.id")
                                    ->join("pro_series s","sk.series_id=s.id")
                                    ->join("pro_category c","s.category_id=c.id")
                                    ->join("pro_brands b","c.brand_id=b.id")
                                    ->where(["p.id"=>$ap[$i]["product"]])
                                    ->value("b.profit");
                                }else if($ap[$i]["sku"]){
                                    $profit=db("pro_sku")->alias("sk")
                                    ->join("pro_series s","sk.series_id=s.id")
                                    ->join("pro_category c","s.category_id=c.id")
                                    ->join("pro_brands b","c.brand_id=b.id")
                                    ->where(["sk.id"=>$ap[$i]["sku"]])
                                    ->value("b.profit");
                                }else if($ap[$i]["series"]){
                                    $profit=db("pro_series")->alias("s")
                                    ->join("pro_category c","s.category_id=c.id")
                                    ->join("pro_brands b","c.brand_id=b.id")
                                    ->where(["s.id"=>$ap[$i]["series"]])
                                    ->value("b.profit");
                                }else if($ap[$i]["category"]){
                                    $profit=db("pro_category")->alias("c")
                                    ->join("pro_brands b","c.brand_id=b.id")
                                    ->where(["c.id"=>$ap[$i]["category"]])
                                    ->value("b.profit");
                                }else{
                                     $profit=db("pro_brands")->where(["id"=>$ap[$i]["brand"]])->value("profit");
                                }
            $up["yujiroi"]=($ap[$i]["totalExpectedSales"]-$ap[$i]["totalBenchmarkSales"])*$profit/100/$up["pizhunhanshui"];
            db("cg_ti_list")->update($up);
          }
          
            }
            $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("y.type=1 and yd.aid=$aid")->field("yd.id")->select();
              if($ys){
                $ysarr=[];
                for($i=0;$i<count($ys);$i++){
                  $ysarr[]=$ys[$i]["id"];
                }
                $ysarr=implode(',',$ysarr);
                db("yusuan_detail")->where("id in($ysarr)")->delete();
              }
      }else if($nodeId=="End1"){
          //结束
          $result=Db::connect('db_config1')->name('tw_hz_task') 
            ->where(['workid'=>$workId])->order("receivetime desc")->find();
            $lastnode=$result["NODENAME"];
            //echo $lastnode;
            if(!($lastnode=="修改申请表"||$lastnode=="归档")){
              Db::table("cg_ti")->where(["id"=>$aid])->update(["status"=>9]);
              $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("Y.type=1 and yd.aid=$aid")->field("yd.id")->select();
              if($ys){
                $ysarr=[];
                for($i=0;$i<count($ys);$i++){
                  $ysarr[]=$ys[$i]["id"];
                }
                $ysarr=implode(',',$ysarr);
                db("yusuan_detail")->where("id in($ysarr)")->update(["type"=>0]);
              }
            }
        }else if($nodeId=="Node7"){
         //通过
              Db::table("cg_ti")->where(["id"=>$aid])->update(["status"=>7]);
              $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("Y.type=1 and yd.aid=$aid")->field("yd.id")->select();
              if($ys){
                $ysarr=[];
                for($i=0;$i<count($ys);$i++){
                  $ysarr[]=$ys[$i]["id"];
                }
                $ysarr=implode(',',$ysarr);
                db("yusuan_detail")->where("id in($ysarr)")->update(["type"=>2]);
              }
              $fb=Db::table("cg_ti")->where(["id"=>$aid])->value("sfxyfk");
              if(!$fb){
                db::table("cg_ti_list")->query("update cg_ti_list set fb_shuilv=shuilv,fb_isVAT=isVAT,fb_shijixiaoliang=totalExpectedSales,fb_shijiweishui=pizhunweishui,fb_hanshui=pizhunhanshui,fb_shijitourufeiyong=yjsjtrfy,fb_user=cuser,fb_boxnum=boxnum,hx_status=0 where ti_id=$aid");
              }
            
        }
    }
     /**
     * 出库申请单
     * @return float|int|string
     */
    public function produce_cksqd_SN(){
        //生成编号
        $max = db('cg_cksqd')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //测试接口
    public function back($workId,$nodeId){
           
        // Db::table("test_abs")->insert(["txt"=>$nodeId]);
          $work=Db::table("cg_workflow")->where(["workId"=>$workId])->find();
        $trackId=$work["trackId"];$ywlx=$work["ywlx"];$aid=$work["yw_id"];
        //echo $ywlx;exit;
        if($ywlx<=3||$ywlx==24){
          $this->tiback($aid,$nodeId);
          return;
        }

        //
           // print_r($result);
        $table=$this->typearr[$ywlx]["table"];
        $yusuan=0;
        if($ywlx==8||$ywlx==9){
            $yusuan=Db::table($table)->where(["id"=>$aid])->value("type_id");
        }
        
        
       if($nodeId=="Node3"){
            //拆分人审批
          if($ywlx==18||$ywlx==20||$ywlx==21||$ywlx==22||$ywlx==23)
            Db::table($table)->where(["id"=>$aid])->update(["status"=>4]);
          else
            Db::table($table)->where(["id"=>$aid])->update(["state"=>4]);
       }else if($nodeId=="Node6"){
            //集团领导审批
            if($ywlx==18||$ywlx==20||$ywlx==21||$ywlx==22||$ywlx==23)
            Db::table($table)->where(["id"=>$aid])->update(["status"=>5]);
          else
          Db::table($table)->where(["id"=>$aid])->update(["state"=>5]);
       }else if($nodeId=="Node8"){
            //修改申请表
           
            if($ywlx==18||$ywlx==20||$ywlx==21||$ywlx==22||$ywlx==23){
              Db::table($table)->where(["id"=>$aid])->update(["status"=>2]);
              //echo db($table)->getLastsql();
            }
            
          else{
            Db::table($table)->where(["id"=>$aid])->update(["state"=>2]);
          }
          
          if($ywlx==12){
            $yuan=Db::table("ap_apply")->where(["id"=>$aid])->find();
                  $yuanid=$yuan["yuan_id"];
                  $yuande=Db::table("ap_apply_detail")->where(["apply_id"=>$aid])->field("yuanmingxi")->select();
                  $yuandelist=[];

                  for($i=0;$i<count($yuande);$i++){
                    $yuandelist[]=$yuande[$i]["yuanmingxi"];
                  }
                  //return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                  $str=implode(',',$yuandelist);
                  
                      //Db::table("ap_apply")->where(["id"=>$yuanid])->update(["tag"=>0,"isqxyd"=>0]);
                      //$res2=Db::table("ap_apply")->where(["id"=>$aid])->update(["state"=>9]);
                      //恢复旧单明细
                      $res1=Db::table("ap_apply_detail")->where("id in ($str)")->update(["is_actived"=>1]);
          }
       }else if($nodeId=="Node7"||$nodeId=="End16"){
            //归档
          
            if($ywlx==5||$ywlx==6||$ywlx==7||$ywlx==14||$ywlx==25||$ywlx==27){
                Db::table($table)->where(["id"=>$aid])->update(["state"=>7]);
            }else if($ywlx==26){
              Db::table($table)->where(["id"=>$aid])->update(["state"=>7]);
              $yuanid=Db::table($table)->where(["id"=>$aid])->value("yuanid");
              Db::table($table)->where(["id"=> $yuanid])->update(["tag"=>1]);
            }else if($ywlx==23){
              Db::table($table)->where(["id"=>$aid])->update(["status"=>7]);
              //订单申请，生成出库单
               //生成出库申请单,出库申请单明细
              $order = db('cg_order')->where(['id'=>$aid])->find();
              $ins = [];
              $ins['sn'] = $this->produce_cksqd_SN();
              $ins['sqr'] = session('employee_id');
              $ins['sqrmc'] = db('employee')->where('id',$ins['sqr'])->value('em_name');
              $ins['sqrbm'] = db('department t')->join('department_employee t2','t2.department_id=t.id')->where(['t2.employee_id'=>$ins['sqr']])->value('t.de_name');
              $ins['sqrq'] = date('Y-m-d');
              $ins['ckfs'] = '销售订单';
              $ins['dyck'] = null; //待定
              $ins['wllx'] = null; //待定
              $ins['sfxyfh'] = 1;
              $ins['shdz'] = $order['shdz'];
              $ins['shlxr'] = $order['shr'];
              $ins['shdh'] = $order['dh'];
              $ins['ckdxlx'] = $order['cusType'];
              $ins['ckdx'] = $order['cusName'];
              $ins['ckdx_name'] = $order['khmc'];
              $ins['order_sn'] = $order['sn'];
              $ins['order_id'] = $aid;
              $bool = db('cg_cksqd')->insertGetId($ins);
              $ins2 = [];
              $mx = db('cg_order_list')->where('order_id',$aid)->select();
              $i = 1;
              foreach($mx as $k=>$v){
                  $t = [];
                  $t['cksqd_id'] = $bool;
                  $t['lx'] = $v['kind']==1?3:1;
                  $t['sn'] = $i;
                  $t['title'] = $v['product'];
                  $t['title_name'] = $v['prod_name'];
                  $t['pro_no'] = $v['prod_sn'];
                  $t['unit'] = $v['unit'];
                  $t['sqsl'] = $v['num']?$v['num']:$v['dzsl'];
                  $t['tj'] = $v['tj'];
                  $t['zl'] = $v['zl'];
                  $t['dj'] = $v['xgj'];
                  $t['num'] = $v['num']?$v['num']:$v['dzsl'];
                  $t['zje'] = $v['ysje'];
                  $t['bz'] = $v['beizhu'];
                  $i++;
                  $ins2[] = $t;
              }
              db('cg_cksqd_list')->insertAll($ins2);
            }else if($ywlx==22){
              //取消
              //当前单据审批通过
              Db::table($table)->where(["id"=>$aid])->update(["status"=>7]);
              $yuanid=db($table)->where(["id"=>$aid])->value("old");
              //是否剩余明细补充单据
              
              $nowlist=db("cg_ti_list")->where(["ti_id"=>$aid])->field("refer_id")->select();
              $nowid=[];
              foreach ($nowlist as $k => $v) {
                # code...
                $nowid[]=$v["refer_id"];
              }
              $nowid=implode(',',$nowid);
              $yuanlist=db("cg_ti_list")->where("ti_id=$yuanid and id not in ($nowid)")->select();
              if($yuanlist){
                //生成新单
                $newsn=$this->produceSN();
                $sq=db("cg_ti")->where(["id"=>$aid])->find();
                $sq["status"] = 7;
                $sq["status2"] = null;
                $sq["cate_id"] = 1;
                $sq["old"] = $yuanid;
                $sq["sn"]=$newsn;
                $sq["ctime"]=time();
                $sq["ptime"]=time();
                unset($sq["id"]);
                $newti=db("cg_ti")->insertGetId($sq);
                Db::table($table)->where(["id"=>$aid])->update(["new"=>$newti]);
                //插入新单明细
                $newlist=[];
                $i=0;
                foreach ($yuanlist as $k => $v) {
                  # code...
                  $tmp=$v;
                 //$tmp["refer_id"]=$tmp["id"];
                 $tmp["ti_id"]=$newti;
                 $tmp["sn"]=$i+1;
                 $i++;
                 unset($tmp["id"]);
                 $newlist[]=$tmp;
                }
                db("cg_ti_list")->insertAll($newlist);
                //预算匹配
                 $ys=$this->tiys($newti);
                 if($ys){
                  foreach ($ys as $k => $v) {
                    # code...
                    $ys[$k]["type"]=2;
                  }
                  db("yusuan_detail")->insertAll($ys);
                 }
                 $new=$newti;
              }else{
                $new=$aid;
              }
              //原单取消
              db("cg_ti")->where("id=$yuanid")->update(["new"=>$new,"status2"=>2]);
              //原单预算取消
              $ys1=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("y.type=1 and yd.aid=$yuanid")->field("yd.id")->select();
                  if($ys1){
                    $ysarr1=[];
                    for($i=0;$i<count($ys1);$i++){
                      $ysarr1[]=$ys1[$i]["id"];
                    }
                    $ysarr1=implode(',',$ysarr1);
                    db("yusuan_detail")->where("id in($ysarr1)")->update(["type"=>0]);
                  }
            }else if($ywlx==21){
                //异动
                //当前单据审批通过
                db("cg_ti")->where(["id"=>$aid])->update(["status"=>7]);
                //当前单据预算状态修改
                $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("y.type=1 and yd.aid=$aid")->field("yd.id")->select();
                  if($ys){
                    $ysarr=[];
                    for($i=0;$i<count($ys);$i++){
                      $ysarr[]=$ys[$i]["id"];
                    }
                    $ysarr=implode(',',$ysarr);
                    db("yusuan_detail")->where("id in($ysarr)")->update(["type"=>2]);
                  }
                  $yuanid=db("cg_ti")->where(["id"=>$aid])->value("old");

                //原单改为被异动状态
                db("cg_ti")->where(["id"=>$yuanid])->update(["status2"=>1,"new"=>$aid]);
                //原单预算作废
                $ys1=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("y.type=1 and yd.aid=$yuanid")->field("yd.id")->select();
                  if($ys1){
                    $ysarr1=[];
                    for($i=0;$i<count($ys1);$i++){
                      $ysarr1[]=$ys1[$i]["id"];
                    }
                    $ysarr1=implode(',',$ysarr1);
                    db("yusuan_detail")->where("id in($ysarr1)")->update(["type"=>0]);
                  }
            }else if($ywlx==20){
                Db::table($table)->where(["id"=>$aid])->update(["status"=>7]);
            }else if($ywlx==18){
            $de=db("cg_ti_hexiao_list")->where(["hx_id"=>$aid])->select();$did1=[];$did2=[];

            for($i=0;$i<count($de);$i++){
              if($de[$i]["yuebuhexiao"])
                $did2[]=$de[$i]["list_id"];
              else
                $did1[]=$de[$i]["list_id"];
            }
            if($did1){
                $did1=implode(',',$did1);
                $arr=db("cg_ti_list")->where("id in ($did1)")->select();
                for($i=0;$i<count($arr);$i++){
                  $up["id"]=$arr[$i]["id"];
                  if($arr[$i]["hx_yihexiao"]){
                    $up["hx_yihexiao"]=$arr[$i]["hx_sqz"]+$arr[$i]["hx_yihexiao"];
                  }else{
                    $up["hx_yihexiao"]=$arr[$i]["hx_sqz"];
                  }
                  $up["hx_sqz"]=0;
                  if($arr[$i]["hx_yihexiao2"]){
                    $up["hx_yihexiao2"]=$arr[$i]["hx_sqhs"]+$arr[$i]["hx_yihexiao2"];
                  }else{
                    $up["hx_yihexiao2"]=$arr[$i]["hx_sqhs"];
                  }
                  $up["hx_sqhs"]=0;
                  if($arr[$i]["hx_sjhxje"]){
                    $up["hx_sjhxje"]=$arr[$i]["hx_sqsj"]+$arr[$i]["hx_sjhxje"];
                  }else{
                    $up["hx_sjhxje"]=$arr[$i]["hx_sqsj"];
                  }
                  $up["hx_sqsj"]=0;
                  $up["hx_status"]=0;
                  Db("cg_ti_list")->update($up);
                }
            }
             if($did2){
                $did1=implode(',',$did2);
                $arr=db("cg_ti_list")->where("id in ($did1)")->select();
                for($i=0;$i<count($arr);$i++){
                  $up["id"]=$arr[$i]["id"];
                  if($arr[$i]["hx_yihexiao"]){
                    $up["hx_yihexiao"]=$arr[$i]["hx_sqz"]+$arr[$i]["hx_yihexiao"];
                  }else{
                    $up["hx_yihexiao"]=$arr[$i]["hx_sqz"];
                  }
                  $up["hx_sqz"]=0;
                  if($arr[$i]["hx_yihexiao2"]){
                    $up["hx_yihexiao2"]=$arr[$i]["hx_sqhs"]+$arr[$i]["hx_yihexiao2"];
                  }else{
                    $up["hx_yihexiao2"]=$arr[$i]["hx_sqhs"];
                  }
                  $up["hx_sqhs"]=0;
                  if($arr[$i]["hx_sjhxje"]){
                    $up["hx_sjhxje"]=$arr[$i]["hx_sqsj"]+$arr[$i]["hx_sjhxje"];
                  }else{
                    $up["hx_sjhxje"]=$arr[$i]["hx_sqsj"];
                  }
                  $up["hx_sqsj"]=0;
                  $up["hx_status"]=2;
                  Db("cg_ti_list")->update($up);
                }
            }
            
           Db::table($table)->where(["id"=>$aid])->update(["status"=>7]);
           
          }
          else if($ywlx==17){
            $ti_id=Db::table($table)->where(["id"=>$aid])->value("apply_id");
            $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid={$ti_id} and y.type=1 and yd.type=2")->field("yd.*")->select();
            //print_r($ys);exit;
            for($i=0;$i<count($ys);$i++){
              $sj=db("cg_ti_list")->where(["id"=>$ys[$i]["did"]])->value("fb_shijitourufeiyong");
              $up["id"]=$ys[$i]["id"];$up["jine"]=$sj/$ys[$i]["zongtianshu"]*$ys[$i]["tianshu"];
              db("yusuan_detail")->update($up);
            }

            Db::table($table)->where(["id"=>$aid])->update(["state"=>7]);
            Db::table("cg_ti_list")->where(["ti_id"=>$ti_id])->update(["hx_status"=>0]);
          }else if($ywlx==19){
            $updata["id"]=$aid;$updata["state"]=7;
            $apids=Db::table("apti_fp_detail")->where(["fp_id"=>$aid])->field("hexiao_id,fp_no")->select();
            
            
              Db::table("apti_fp_apply")->update($updata);
              for($i=0;$i<count($apids);$i++){
                Db::table("cg_ti_hexiao_list")->where("id={$apids[$i]["hexiao_id"]}")->update(["bu_state"=>2,"youwufapiao"=>1,"fapiaohao"=>$apids[$i]["fp_no"]]);
              }
             
          }else if($ywlx==16){
            $updata["id"]=$aid;$updata["state"]=7;
            $apids=Db::table("apti_fp_detail")->where(["fp_id"=>$aid])->field("hexiao_id,fp_no")->select();
            Db::table("apti_fp_apply")->update($updata);
            for($i=0;$i<count($apids);$i++){
                Db::table("ap_hexiao_detail")->where("id={$apids[$i]["hexiao_id"]}")->update(["bu_state"=>2,"has_fp"=>1,"fp_no"=>$apids[$i]["fp_no"]]);
            }
             
          }else if($ywlx==15){
            Db::table($table)->where(["id"=>$aid])->update(["state"=>7,"is_shengxiao"=>1]);
          }else if($ywlx==13){
              $apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
              $yuanid=$apply["yuan_id"];
              $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid={$yuanid} and y.type=2")->field("yd.id")->select();
                  if($ydid){
                    $ydids=[];
                    for($i=0;$i<count($ydid);$i++){
                      $ydids[]=$ydid[$i]["id"];
                    }
                    $yd=implode(',',$ydids);
                    Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
                  }
               Db::table("ap_apply")->where(["id"=>$yuanid])->update(["next_id"=>$aid,"tag"=>1]);
                 //做预算
                 $ysres=$this->apys($aid);
                 if($ysres){
                    $res2=Db::table("yusuan_detail")->insertAll($ysres);
                }
                 Db::table($table)->where(["id"=>$aid])->update(["state"=>7,"is_shengxiao"=>1,"guidangdate"=>date("Y-m-d H:i:s")]);
          }else if($ywlx==12){
            //Ap取消
            $apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
            $yuanid=$apply["yuan_id"];
            $shenyu=Db::table("ap_apply_detail")->where(["is_deleted"=>0,"is_actived"=>1,"apply_id"=>$yuanid])->select();
            $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid={$yuanid} and y.type=2")->field("yd.id")->select();
                  if($ydid){
                    $ydids=[];
                    for($i=0;$i<count($ydid);$i++){
                      $ydids[]=$ydid[$i]["id"];
                    }
                    $yd=implode(',',$ydids);
                    Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
                  }
            
        //print_r($shenyu);exit;
          if($shenyu){
            //如果有剩余创建新单据
              //生成单号
                 $timenow=date("Ymd");
                  $num=Db::table("ap_apply")->where("no like '$timenow%'")->count();
                   $num++;
                   $strnum=$timenow.sprintf("%05d", $num);
                   //
                   
                   $newdata=$apply;
                   $newdata["no"]=$strnum;$newdata["created_on"]=date("Y-m-d H:i:s");$newdata["is_actived"]=1;$newdata["state"]=7;
                   $newdata["yuan_id"]=$yuanid; $newdata["is_shengxiao"]=1;$newdata["tag"]=0;$newdata["guidangdate"]=date("Y-m-d H:i:s");
                   unset( $newdata["id"]);
                  $res=Db::table("ap_apply")->insertGetId($newdata);
                  //$res=9;
                   $dedata=[];
                   for($i=0;$i<count($shenyu);$i++){
                    $shenyu[$i]["yuanmingxi"]=$shenyu[$i]["id"];
                    $shenyu[$i]["detail_no"]=$i+1;
                    $shenyu[$i]["apply_id"]=$res;
                    $tmp=$shenyu[$i];
                    unset($tmp["id"]);
                    $dedata[]=$tmp;
                 }
                 //print_r($dedata);exit;
                 Db::table("ap_apply_detail")->insertAll($dedata);
                 Db::table("ap_apply")->where(["id"=>$yuanid])->update(["next_id"=>$res,"tag"=>2]);
                 //做预算
                 $ysres=$this->apys($res);
                 if($ysres){
                    $res2=Db::table("yusuan_detail")->insertAll($ysres);
                }
            }else{
              Db::table("ap_apply")->where(["id"=>$yuanid])->update(["next_id"=>$aid,"tag"=>2]);
            }
            Db::table($table)->where(["id"=>$aid])->update(["state"=>7,"guidangdate"=>date("Y-m-d H:i:s")]);
          }else if($ywlx==11){
            //AP费用申请
            $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=2")->field("yd.id")->select();
            if($ydid){
              $ydids=[];
              for($i=0;$i<count($ydid);$i++){
                $ydids[]=$ydid[$i]["id"];
              }
              $yd=implode(',',$ydids);
              Db::table("yusuan_detail")->query("update yusuan_detail set type=2 where id in ($yd)");
            }
            Db::table($table)->where(["id"=>$aid])->update(["state"=>7,"is_shengxiao"=>1,"guidangdate"=>date("Y-m-d H:i:s")]);
          }else if($ywlx==10){
            //日常费用报销
            $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=3")->field("yd.id")->select();
            if($ydid){
              $ydids=[];
              for($i=0;$i<count($ydid);$i++){
                $ydids[]=$ydid[$i]["id"];
              }
              $yd=implode(',',$ydids);
              Db::table("yusuan_detail")->query("update yusuan_detail set type=2 where id in ($yd)");
            }
            Db::table($table)->where(["id"=>$aid])->update(["state"=>7,"guidangdate"=>date("Y-m-d H:i:s")]);
          }else if($ywlx==8||$ywlx==9){
                //echo $ywlx;
                if($yusuan==2||$yusuan==3||$yusuan==4){
                    //预算
                    //预算通过则录入
                    $yusuantype=$yusuan-1;
                    $apply=Db::table("target_apply_detail")->where(["apply_id"=>$aid])->select();
                    //print_r($apply);exit;
                    $adddata=[];$ysarr=[];
                    //讲新增加的预算加入数据库
                    for($i=0;$i<count($apply);$i++){
                        $tmp=[];
                        if($apply[$i]["channel1"])
                            $tmp["channel1"]=$apply[$i]["channel1"];
                        else
                            $tmp["channel1"]=null;
                        if($apply[$i]["channel2"])
                            $tmp["channel2"]=$apply[$i]["channel2"];
                        else
                            $tmp["channel2"]=null;
                        if($apply[$i]["fenqu"])
                            $tmp["fenqu"]=$apply[$i]["fenqu"];
                        else
                            $tmp["fenqu"]=null;
                        if($apply[$i]["sheng"])
                            $tmp["sheng"]=$apply[$i]["sheng"];
                        else
                            $tmp["sheng"]=null;
                        if($apply[$i]["shi"])
                            $tmp["shi"]=$apply[$i]["shi"];
                        else
                            $tmp["shi"]=null;
                        if($apply[$i]["jingxiao"])
                            $tmp["jingxiao"]=$apply[$i]["jingxiao"];
                        else
                            $tmp["jingxiao"]=null;
                        if($apply[$i]["xitong"])
                            $tmp["xitong"]=$apply[$i]["xitong"];
                        else
                            $tmp["xitong"]=null;
                        if($apply[$i]["wangdian"])
                            $tmp["wangdian"]=$apply[$i]["wangdian"];
                        else
                            $tmp["wangdian"]=null;
                        if($apply[$i]["pinpai"])
                            $tmp["pinpai"]=$apply[$i]["pinpai"];
                        else
                            $tmp["pinpai"]=null;
                        if($apply[$i]["pinlei"])
                            $tmp["pinlei"]=$apply[$i]["pinlei"];
                        else
                            $tmp["pinlei"]=null;
                        if($apply[$i]["xilie"])
                            $tmp["xilie"]=$apply[$i]["xilie"];
                        else
                            $tmp["xilie"]=null;
                        if($apply[$i]["yijifeiyong"])
                            $tmp["yijifeiyong"]=$apply[$i]["yijifeiyong"];
                        else
                            $tmp["yijifeiyong"]=null;
                        if($apply[$i]["erjifeiyong"])
                            $tmp["erjifeiyong"]=$apply[$i]["erjifeiyong"];
                        else
                            $tmp["erjifeiyong"]=null;
                        if($apply[$i]["sanjifeiyong"])
                            $tmp["sanjifeiyong"]=$apply[$i]["sanjifeiyong"];
                        else
                            $tmp["sanjifeiyong"]=null;
                        if($apply[$i]["people"])
                            $tmp["people"]=$apply[$i]["people"];
                        else
                            $tmp["people"]=null;
                        if($apply[$i]["depart"])
                            $tmp["depart"]=$apply[$i]["depart"];
                        else
                            $tmp["depart"]=null;
                        if($apply[$i]["cainian"])
                            $tmp["cainian"]=$apply[$i]["cainian"];
                        else
                            $tmp["cainian"]=null;
                        if($apply[$i]["yijikaoheqi"])
                            $tmp["yijikaoheqi"]=$apply[$i]["yijikaoheqi"];
                        else
                            $tmp["yijikaoheqi"]=null;
                        if($apply[$i]["erjikaoheqi"])
                            $tmp["erjikaoheqi"]=$apply[$i]["erjikaoheqi"];
                        else
                            $tmp["erjikaoheqi"]=null;
                        $tmp["type"]=$yusuantype;
                        //print_r($tmp);
                        $ys=Db::table("yusuan")->where($tmp)->find();
                        //print_r($ys);
                        if($ys){
                            $yid=$ys["id"];
                        }else{
                            $tmp["jine"]=0;
                            $yid=Db::table("yusuan")->insertGetId($tmp);
                        }
                        $adddata[]=["aid"=>$aid,"did"=>$apply[$i]["id"],"feiyong"=>$apply[$i]["feiyong"],"state"=>1,"yid"=>$yid];
                        if(!in_array($yid, $ysarr)){
                            $ysarr[]=$yid;
                        }
                    }
                    //exit;
                    Db::table("yusuan_apply")->insertAll($adddata);
                    //处理异动预算
                    if($ywlx==9){
                        $yuanid=Db::table($table)->where(["id"=>$aid])->value("yuanid");
                        $yuanyusuan=Db::table("yusuan_apply")->where(["aid"=>$yuanid])->select();
                        for($i=0;$i<count($yuanyusuan);$i++){
                            if(!in_array($yuanyusuan[$i]["yid"], $ysarr)){
                                $ysarr[]=$yuanyusuan[$i]["yid"];
                            }
                        }
                        Db::table("yusuan_apply")->where(["aid"=>$yuanid])->update(["state"=>0]);

                    }
                    $yids=implode(',',$ysarr);
                    Db::Table("yusuan")->query("update yusuan y set jine=(select sum(feiyong) from yusuan_apply as a where a.yid=y.id and a.state=1)");
                    Db::table($table)->where(["id"=>$aid])->update(["state"=>7]);
                    if($ywlx==9){
                        
                        Db::table($table)->where(["id"=>$yuanid])->update(["islock"=>1,"tag"=>1]);
                    }
                }else{
                    //费预算
                    
                    Db::table($table)->where(["id"=>$aid])->update(["state"=>7]);
                    if($ywlx==9){
                        $yuanid=Db::table($table)->where(["id"=>$aid])->value("yuanid");
                        Db::table($table)->where(["id"=>$yuanid])->update(["islock"=>1,"tag"=>1]);
                    }
                    
                }
            }else{
                //echo $ywlx;
            }
            

           // print_r($data1);
       }else if($nodeId=="End1"){
            //结束
            $result=Db::connect('db_config1')->name('tw_hz_task') 
            ->where(['workid'=>$workId])->order("receivetime desc")->find();
            $lastnode=$result["NODENAME"];

           // $istmp=db("workflow_tmp")->where(["workId"=>$workId])->count();
            //echo $lastnode;
           if(!($lastnode=="修改申请表"||$lastnode=="归档")){
                //否决
                if($ywlx==5||$ywlx==6||$ywlx==7||$ywlx==8||$ywlx==25||$ywlx==27){
                    Db::table($table)->where(["id"=>$aid])->update(["state"=>9]);
                }else if($ywlx==26){
                  Db::table($table)->where(["id"=>$aid])->update(["state"=>9]);
                  $yuanid=Db::table($table)->where(["id"=>$aid])->value("yuanid");
                  Db::table($table)->where(["id"=> $yuanid])->update(["tag"=>0,"islock"=>0,"nextid"=>null]);
                }else if($ywlx==23){
                  //订单否决
                  db("cg_order")->where(["id"=>$aid])->update(["status"=>9]);
                  //补货补费支付清除
                  
                }else if($ywlx==22){
                  //单据否决
                  db("cg_ti")->where(["id"=>$aid])->update(["status"=>9]);
                   $yuanid=db("cg_ti")->where(["id"=>$aid])->value("old");

                  //解锁原单
                  db("cg_ti")->where(["id"=>$yuanid])->update(["is_ydqx"=>0]);
                }else if($ywlx==21){
                  //单据否决
                  db("cg_ti")->where(["id"=>$aid])->update(["status"=>9]);
              
                  $yuanid=db("cg_ti")->where(["id"=>$aid])->value("old");

                  //解锁原单
                  db("cg_ti")->where(["id"=>$yuanid])->update(["is_ydqx"=>0]);
                  //单据预算否决
                    
                $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("y.type=1 and yd.aid=$aid")->field("yd.id")->select();
                  if($ys){
                    $ysarr=[];
                    for($i=0;$i<count($ys);$i++){
                      $ysarr[]=$ys[$i]["id"];
                    }
                    $ysarr=implode(',',$ysarr);
                    db("yusuan_detail")->where("id in($ysarr)")->delete();
                  }
                }else if($ywlx==20){
                    Db::table($table)->where(["id"=>$aid])->update(["status"=>9]);
                }else if($ywlx==9){
                    $yuanid=Db::table($table)->where(["id"=>$aid])->value("yuanid");
                    Db::table($table)->where(["id"=>$yuanid])->update(["tag"=>0,"nextid"=>null,"islock"=>0]);
                    Db::table($table)->where(["id"=>$aid])->update(["state"=>9]);
                }else if($ywlx==10){
                 $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=3")->field("yd.id")->select();
                  if($ydid){
                    $ydids=[];
                    for($i=0;$i<count($ydid);$i++){
                      $ydids[]=$ydid[$i]["id"];
                    }
                    $yd=implode(',',$ydids);
                    Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
                  }
                  Db::table($table)->where(["id"=>$aid])->update(["state"=>9]);
              }else if($ywlx==11){
                 $ydid=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("yd.aid=$aid and y.type=2")->field("yd.id")->select();
                  if($ydid){
                    $ydids=[];
                    for($i=0;$i<count($ydid);$i++){
                      $ydids[]=$ydid[$i]["id"];
                    }
                    $yd=implode(',',$ydids);
                    Db::table("yusuan_detail")->query("update yusuan_detail set type=0 where id in ($yd)");
                  }
                  Db::table($table)->where(["id"=>$aid])->update(["state"=>9]);
              }else if($ywlx==12){
                  $yuan=Db::table("ap_apply")->where(["id"=>$aid])->find();
                  $yuanid=$yuan["yuan_id"];
                  $yuande=Db::table("ap_apply_detail")->where(["apply_id"=>$aid])->field("yuanmingxi")->select();
                  $yuandelist=[];

                  for($i=0;$i<count($yuande);$i++){
                    $yuandelist[]=$yuande[$i]["yuanmingxi"];
                  }
                  //return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                  $str=implode(',',$yuandelist);
                  
                      Db::table("ap_apply")->where(["id"=>$yuanid])->update(["tag"=>0,"isqxyd"=>0]);
                      $res2=Db::table("ap_apply")->where(["id"=>$aid])->update(["state"=>9]);
                      //恢复旧单明细
                      $res1=Db::table("ap_apply_detail")->where("id in ($str)")->update(["is_actived"=>1]);
                    
                      
              }else if($ywlx==13){
                  $yuan=Db::table("ap_apply")->where(["id"=>$aid])->find();
                  $yuanid=$yuan["yuan_id"];
                  Db::table("ap_apply")->where(["id"=>$yuanid])->update(["tag"=>0,"isqxyd"=>0]);
                      $res2=Db::table("ap_apply")->where(["id"=>$aid])->update(["state"=>9]);
              }else if($ywlx==14){
                Db::table("ap_fankui")->where(["id"=>$aid])->update(["state"=>9]);
                Db::table("ap_apply_detail")->where(["fankui_id"=>$aid])->update(["fankui_id"=>0,"fankuixiaoliang"=>0,"fankuiremark"=>null]);
              }else if($ywlx==15){
                 $arr=Db::table("ap_hexiao_detail")->where(["hexiao_id"=>$aid])->select();
                for($i=0;$i<count($arr);$i++){
                    $tmp=Db::table("ap_apply_detail")->where(["id"=>$arr[$i]["detail_id"]])->find();
                    $upde["id"]=$arr[$i]["detail_id"];
                    $upde["hexiao"]=$tmp["hexiao"]-$arr[$i]["hexiao_weishui"];
                    if($arr[$i]["buyu_he"])
                        $upde["buyu_he"]=0;
                    Db::table("ap_apply_detail")->update($upde);
                }
                Db::table("ap_hexiao_apply")->where(["id"=>$aid])->update(["state"=>9]);
              }else if($ywlx==16){
                $updata["id"]=$aid;$updata["state"]=9;
                $apids=Db::table("apti_fp_detail")->where(["fp_id"=>$aid])->field("hexiao_id")->select();
                $arr=[];
                for($i=0;$i<count($apids);$i++){
                  $arr[]=$apids[$i]["hexiao_id"];
                }
                //print_r($arr);exit;
                $str=implode(',',$arr);
              
                Db::table("apti_fp_apply")->update($updata);
                Db::table("ap_hexiao_detail")->where("id in ($str)")->update(["bu_state"=>0]);
                
              }else if($ywlx==19){
                $updata["id"]=$aid;$updata["state"]=9;
                $apids=Db::table("apti_fp_detail")->where(["fp_id"=>$aid])->field("hexiao_id")->select();
                $arr=[];
                for($i=0;$i<count($apids);$i++){
                  $arr[]=$apids[$i]["hexiao_id"];
                }
                //print_r($arr);exit;
                $str=implode(',',$arr);
                
                  Db::table("apti_fp_apply")->update($updata);
                  Db::table("cg_ti_hexiao_list")->where("id in ($str)")->update(["bu_state"=>0]);
                
              }
            }else{
               // db("workflow_tmp")->where(["workId"=>$workId])->delete();
            }
       }
       
        
    }
    ///
    public function nodeback($workId,$nodeId){


    }
     //ap预算匹配
    public function apys($aid){
        $apply=Db::table("ap_apply")->where(["id"=>$aid])->find();
        $applyde=Db::table("ap_apply_detail")->where(["apply_id"=>$aid,"is_deleted"=>0])->select();
        $aptar=Db::table("target_format")->where(["type_id"=>3])->find();
        if($aptar){
            $yusuan=[];

            for($i=0;$i<count($applyde);$i++){
                $where="type=2 ";
                $sanjifeiyong=$applyde[$i]["feiyong_id"];
                $erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
                $yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
                $start=strtotime($applyde[$i]["start_time"]);
                $end=strtotime($applyde[$i]["end_time"]);
                $tianshu=($end-$start)/24/3600+1;
                //echo $tianshu;
                if($aptar["channel_id"]){
                    $where.="and channel1={$apply["channel_id"]} ";
                }
                if($aptar["product_id"]){
                    if($aptar["product_id"]==11){
                        $where.="and pinpai={$applyde[$i]["brand"]} and pinlei is null and xilie is null ";
                    }else if($aptar["product_id"]==12){
                        if($applyde[$i]["category"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie is null ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }else if($aptar["product_id"]==13){
                        if($applyde[$i]["series"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie={$applyde[$i]["series"]} ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }
                }else{
                    $where.="and pinpai is null and pinlei is null and xilie is null ";
                }
                if($aptar["area_id"]||$aptar["client_id"]){
                    if($aptar["area_id"]==20){
                        $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng is null and shi is null and jingxiao is null ";
                    }else if($aptar["area_id"]==21){
                        if($applyde[$i]["sheng"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi is null and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["area_id"]==22){
                        if($applyde[$i]["shi"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["client_id"]==8){
                        if($applyde[$i]["jxs"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao={$applyde[$i]["jxs"]} ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }
                }else{
                    $where.="and fenqu is null and sheng is null and shi is null and jingxiao is null ";
                }
                if($aptar["feiyong_id"]){
                    if($aptar["feiyong_id"]==16){
                        $where.="and sanjifeiyong=$sanjifeiyong ";
                    }else if($aptar["feiyong_id"]==15){
                        $where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
                    }else{
                        $where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
                    }
                }else{
                    $where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
                }
                if($aptar["kaoheqi"]==18){
                    //二级考核期
                    $kaohes=Db::table("cg_kaoheqi2")->alias("k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->where("k2.endtime>=$start and k2.starttime<=$end")->field("k2.id,k2.title,k2.pid,k1.cid,k2.starttime,k2.endtime")->select();
                    for($j=0;$j<count($kaohes);$j++){
                        $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                        $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                        $ts=($jisuanend-$jisuanstart)/24/3600+1;
                        //echo "-".$ts;
                        $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["pid"]} and erjikaoheqi={$kaohes[$j]["id"]}";
                        //echo $fullwhere;exit;
                        $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                        if($yusuanpipei){
                            $hanshui=($applyde[$i]["pifuzonge"]+$applyde[$i]["pifuzonge"]*$applyde[$i]["shuilv"]/100)/$tianshu*$ts;
                            $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>2,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                            $yusuan[]=$tmpy;
                        }
                    }
                }else{
                    //一级考核期
                    $kaohes=Db::table("cg_kaoheqi1")->where("endtime>=$start and starttime<=$end")->field("id,title,cid,starttime,endtime")->select();
                    for($j=0;$j<count($kaohes);$j++){
                        $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                        $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                        $ts=($jisuanend-$jisuanstart)/24/3600+1;
                        $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["id"]} and erjikaoheqi is null";
                        //echo $fullwhere;exit;
                        $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                        if($yusuanpipei){
                            $hanshui=($applyde[$i]["pifuzonge"]+$applyde[$i]["pifuzonge"]*$applyde[$i]["shuilv"]/100)/$tianshu*$ts;
                            $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>2,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                            $yusuan[]=$tmpy;
                        }
                    }
                }
            }
            //print_r($yusuan);exit;
            return $yusuan;
        }else{
            return 0;//未设定格式
        }
       
    }
     //ti预算匹配
    public function tiys($aid){
        $apply=Db::table("cg_ti")->where(["id"=>$aid])->find();
        $type_id=$apply["type_id"];
        $applyde=Db::table("cg_ti_list")->where(["ti_id"=>$aid])->select();
        $aptar=Db::table("target_format")->where(["type_id"=>2])->find();
        $jxs=Db::table("cg_jxs")->where(["id"=>$apply["jxs_id"]])->field("zoning,provice,city")->find();

        if($aptar){
            $yusuan=[];
           //echo count($applyde);exit;
            for($i=0;$i<count($applyde);$i++){
                if($type_id==1){
                    $applyde[$i]["product"]=$applyde[$i]["f1"];
                    $year=$applyde[$i]["year"];
                    $month=$applyde[$i]["month"];
                    $applyde[$i]["start"]=strtotime("{$year}-{$month}-15");
                    $applyde[$i]["end"]=strtotime("{$year}-{$month}-15");
                }
               // echo $i;exit;
                if($applyde[$i]["product"]){
                    $applyde[$i]["sku"]=Db::table("pro_products")->where(["id"=>$applyde[$i]["product"]])->value("sku_id");
                }
                if($applyde[$i]["sku"]){
                    $applyde[$i]["series"]=Db::table("pro_sku")->where(["id"=>$applyde[$i]["sku"]])->value("series_id");
                }
                if($applyde[$i]["series"]){
                    $applyde[$i]["category"]=Db::table("pro_series")->where(["id"=>$applyde[$i]["series"]])->value("category_id");
                }
                if($applyde[$i]["category"]){
                    $applyde[$i]["brand"]=Db::table("pro_category")->where(["id"=>$applyde[$i]["category"]])->value("brand_id");
                }
                $applyde[$i]["jxs"]=$apply["jxs_id"];
                $applyde[$i]["fenqu"]=$jxs["zoning"];
                $applyde[$i]["sheng"]=$jxs["provice"];
                $applyde[$i]["shi"]=$jxs["city"];
                $where="type=1 ";
                $sanjifeiyong=$applyde[$i]["feetype"];
                $erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
                $yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
                $channel=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("channeltypes");
                $channel=unserialize($channel);
                $channelstr=implode(',',$channel);
                //print_r($channel);exit;
                $start=$applyde[$i]["start"];
                $end=$applyde[$i]["end"];
                $tianshu=($end-$start)/24/3600+1;
                if($aptar["product_id"]){
                    if($aptar["product_id"]==11){
                        $where.="and pinpai={$applyde[$i]["brand"]} and pinlei is null and xilie is null ";
                    }else if($aptar["product_id"]==12){
                        if($applyde[$i]["category"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie is null ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }else if($aptar["product_id"]==13){
                        if($applyde[$i]["series"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie={$applyde[$i]["series"]} ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }
                }else{
                    $where.="and pinpai is null and pinlei is null and xilie is null ";
                }  
                if($aptar["area_id"]||$aptar["client_id"]){
                    if($aptar["area_id"]==20){
                        $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng is null and shi is null and jingxiao is null ";
                    }else if($aptar["area_id"]==21){
                        if($applyde[$i]["sheng"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi is null and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["area_id"]==22){
                        if($applyde[$i]["shi"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["client_id"]==8){
                        if($applyde[$i]["jxs"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao={$applyde[$i]["jxs"]} ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }
                }else{
                    $where.="and fenqu is null and sheng is null and shi is null and jingxiao is null ";
                }
                if($aptar["feiyong_id"]){
                    if($aptar["feiyong_id"]==16){
                        $where.="and sanjifeiyong=$sanjifeiyong ";
                    }else if($aptar["feiyong_id"]==15){
                        $where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
                    }else{
                        $where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
                    }
                }else{
                    $where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
                }
               /* 
                if($aptar["channel_id"]){
                    $where.="and channel1 in ($channelstr) ";
                }*/
               //echo $where;echo "<br/>";exit;
               if($aptar["kaoheqi"]==18){
                ///echo "---";
                    //二级考核期
                    $kaohes=Db::table("cg_kaoheqi2")->alias("k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->where("k2.endtime>=$start and k2.starttime<=$end")->field("k2.id,k2.title,k2.pid,k1.cid,k2.starttime,k2.endtime")->select();
                    $hask=[];
                    for($j=0;$j<count($kaohes);$j++){
                        $hask[]=$kaohes[$j]["id"];
                    }
                    $kstr=implode(',',$hask);
                     $maxc=0;$maxcys=0;
                     //print_r($channel);
                    for($j=0;$j<count($channel);$j++){
                        $tmpwhere=$where."and channel1={$channel[$j]} and erjikaoheqi in ($kstr) ";
                       // echo $tmpwhere."<br/>";
                        $tmpys=Db::table("yusuan")->where($tmpwhere)->sum("jine");
                        //echo db("yusuan")->getLastsql()."<br/>";
                        if($tmpys){
                            if($tmpys>$maxc){
                                $maxc=$channel[$j];
                                $maxcys=$tmpys;
                            }
                        }else{
                            $tmpys=0;
                        }
                    }
                     if($maxc){
                        //echo $maxc;
                        $where.="and channel1=$maxc ";
                        for($j=0;$j<count($kaohes);$j++){
                            $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                            $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                            $ts=($jisuanend-$jisuanstart)/24/3600+1;
                            //echo "-".$ts;
                            $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["pid"]} and erjikaoheqi={$kaohes[$j]["id"]}";
                           // echo $fullwhere;echo "<br/>";//exit;
                            $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                            if($yusuanpipei){
                                $hanshui=($applyde[$i]["yjsjtrfy"])/$tianshu*$ts;
                                $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>1,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                                $yusuan[]=$tmpy;
                            }
                        }
                    }else{
                       // break;
                    }
                }else{
                   // echo "---";
                    //一级考核期
                    $kaohes=Db::table("cg_kaoheqi1")->where("endtime>=$start and starttime<=$end")->field("id,title,cid,starttime,endtime")->select();
                    $hask=[];
                    for($j=0;$j<count($kaohes);$j++){
                        $hask[]=$kaohes[$j]["id"];
                    }
                    $kstr=implode(',',$hask);
                    $maxc=0;$maxcys=0;
                    for($j=0;$j<count($channel);$j++){
                        $tmpwhere=$where."and channel1={$channel[$j]} and yijikaoheqi in ($kstr) ";
                        //echo $tmpwhere."<br/>";
                        $tmpys=Db::table("yusuan")->where($tmpwhere)->sum("jine");
                        if($tmpys){
                            if($tmpys>$maxc){
                                $maxc=$channel[$j];
                                $maxcys=$tmpys;
                            }
                        }else{
                            $tmpys=0;
                        }
                        //echo $tmpys."<br>";
                    }
                    if($maxc){
                        //echo $maxc;
                        $where.="and channel1=$maxc ";
                        for($j=0;$j<count($kaohes);$j++){
                            $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                            $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                            $ts=($jisuanend-$jisuanstart)/24/3600+1;
                            //echo "-".$ts;
                            $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and  yijikaoheqi={$kaohes[$j]["id"]} and erjikaoheqi is null";
                            //echo $fullwhere;echo "<br/>";//exit;
                            $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                            if($yusuanpipei){
                                $hanshui=($applyde[$i]["yjsjtrfy"])/$tianshu*$ts;
                                $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>1,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                                $yusuan[]=$tmpy;
                            }
                        }
                    }else{
                       // break;
                    }

                } 
              //  echo $i;
            }
            //exit;
            //print_r($yusuan);exit;
            return $yusuan;
        }else{
            return 0;//未设定格式
        }
       
    }
}
